/**
 * 微信小程序通过STS直传阿里云OSS
 *（uniapp版上传，小程序原生需要将uni.XXX替换为wx.XXX）
 *
 * @param {filePath} 图片临时地址
 * @param {option|Object} OSS和STS配置
 * @param {savePath} oss中的文件目录
 * @param {AccessKeySecret} 服务端返回的STS中的AccessKeySecret
 * @param {SecurityToken} 服务端返回的STS中的SecurityToken
 * @param {AccessKeyId} 服务端返回的STS中的AccessKeyId
 * @param {bucket} 存储桶
 * @param {area} 地区
 * @return {string|boolean} 成功返回文件地址，失败返回false
 */

import crypto from 'crypto-js';
import { Base64 } from 'js-base64';

function upload(
	filePath,
	option = {
		KeyPath,
		AccessKeySecret,
		SecurityToken,
		AccessKeyId,
		Url,
	},
) {
	const date = new Date();
	date.setMinutes(date.getMinutes() + 5);
	// date.setHours(date.getHours() + 1);
	const policyText = {
		expiration: date.toISOString(), // 设置policy过期时间。
		conditions: [['content-length-range', 0, 1024 * 1024 * 1024 * 1024]],
	};
	// 策略应该后端生成....
	const policy = Base64.encode(JSON.stringify(policyText)); // policy必须为base64的string。
	const signature = computeSignature(option.AccessKeySecret, policy);
	const formData = {
		OSSAccessKeyId: option.AccessKeyId,
		signature,
		policy,
		'x-oss-security-token': option.SecurityToken,
		key: option.KeyPath,
		success_action_status: 200,
	};
	return new Promise(async (resolve, reject) => {
		uni.uploadFile({
			url: option.Url,
			filePath: filePath,
			name: 'file',
			formData: formData,
			success: (res) => {
				console.log('上传成功结果: ', res);
				resolve(option.KeyPath);
			},
			fail: (err) => {
				console.log('上传失败结果: ', res);
				reject(false);
			},
		});
	});
}

// 签名
function computeSignature(accessKeySecret, canonicalString) {
	return crypto.enc.Base64.stringify(crypto.HmacSHA1(canonicalString, accessKeySecret));
}

export default {
	upload,
};
